﻿namespace GenericHtml
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.SessionState;
    using WLFramework.Json;

    public class AjaxHttpHandler : IHttpHandler, IRequiresSessionState, ILoginInfo
    {
        public static bool IsDebug = true;

        public UserInfo LoginUser { get; set; }

        public virtual void OnProcessRequest(HttpContext context) { }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.CacheControl = "no-cache";
            JSON.Instance.Parameters.EnableAnonymousTypes = true;

            try
            {
                if (!context.Request.IsAuthenticated)
                {
                    context.Response.Write(JSON.Instance.ToJSON(GenericConfigure.LoginFailed));
                    return;
                }

                this.LoginUser = context.Session["current_user"] as UserInfo;
                if (this.LoginUser == null)
                {
                    // 登录失效 处理
                    context.Response.Write(JSON.Instance.ToJSON(GenericConfigure.LoginFailed));
                    return;
                }

                this.OnProcessRequest(context);
            }
            catch (Exception ex)
            {
                if (IsDebug)
                {
                    context.Response.Write(
                        JSON.Instance.ToJSON(new JSONResult("failed", ex.Message)));
                }
            }
        }

        public static bool IsNullOrWhiteSpace(string value)
        {
            if (value == null || value.Length == 0)
            {
                return true;
            }

            for (int i = 0; i < value.Length; i++)
            {
                if (!char.IsWhiteSpace(value[i]))
                    return false;
            }

            return true;
        }
    }
}